﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// lua代码使用，代替InputField手动指定回调事件功能
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Bind/Event Bind InputField")]
    [RequireComponent(typeof(InputField))]
    public sealed class UIEventBindInputField : UIEventBind
    {
        [SerializeField]
        [EventName]
        private string valueChangedEventName;

        [SerializeField]
        [EventName]
        private string endEditEventName;

        private InputField _input;
        private SignalEvent _signalChanagedevent, _signalEditorevent;


        protected override void Awake()
        {
            base.Awake();
            this._input = base.GetComponent<InputField>();
        }

        private void OnEnable()
        {
            this._input.onValueChanged.AddListener(OnValueChanged);
            this._input.onEndEdit.AddListener(OnEndEdit);
        }

        private void OnDisable()
        {
            this._input.onValueChanged.RemoveListener(OnValueChanged);
            this._input.onEndEdit.RemoveListener(OnEndEdit);
        }

        protected override void RefreshBind()
        {
            this._signalChanagedevent = base.GetSignalEvent(this.valueChangedEventName);
            this._signalEditorevent = base.GetSignalEvent(this.endEditEventName);
        }
        /// <summary>
        /// 输入字符事件
        /// </summary>
        /// <param name="txt"></param>
        private void OnValueChanged(string txt)
        {
            SignalEvent _event = this.FindSignalChangeEvent();
            if (_event != null)
            {
                _event.Excute(txt);
            }
        }
        /// <summary>
        /// 字符输入结束事件
        /// </summary>
        /// <param name="txt"></param>
        private void OnEndEdit(string txt)
        {
            SignalEvent _event = this.FindSignalEndEditorEvent();
            if (_event != null)
            {
                _event.Excute(txt);
            }
        }

        private SignalEvent FindSignalChangeEvent()
        {
            if (this._signalChanagedevent == null)
            {
                this._signalChanagedevent = base.GetSignalEvent(this.valueChangedEventName);
            }
            return this._signalChanagedevent;
        }
        private SignalEvent FindSignalEndEditorEvent()
        {
            if (this._signalEditorevent == null)
            {
                this._signalEditorevent = base.GetSignalEvent(this.endEditEventName);
            }
            return this._signalEditorevent;
        }


    }
}

